<template>
  <div>
    <div>
      <el-button type="primary" @click="GenerateImg">下载</el-button>
    </div>
    <div class="image">你猜猜看这是一段文字还是一张图片？猜对了有糖果吃~</div>
  </div>
</template>
<script>
import { getDateTime } from "@/utils/getDateTime";
import html2canvas from "html2canvas";
export default {
  data() {
    return {
      time: getDateTime(1),
      year: null,
      content: "",
      bottom: "",
      list: [],
      path: "",
    };
  },
  created() {},
  methods: {
    //转换成图片
    GenerateImg() {
      let canvas = document.querySelector(".image"); //先获取要截取页面的DOM
      let that = this;
      html2canvas(canvas, { scale: 2, logging: false, useCORS: true }).then(
        function (canvas) {
          let type = "png";
          let imgData = canvas.toDataURL(type);
          // 照片格式处理
          let _fixType = function (type) {
            type = type.toLowerCase().replace(/jpg/i, "jpeg");
            let r = type.match(/png|jpeg|bmp|gif/)[0];
            return "image/" + r;
          };
          imgData = imgData.replace(_fixType(type), "image/octet-stream");
          let filename = `${that.list.company_name}${that.year}年度服务卡.${type}`;
          //   this.list.company_name + this.year + "年度服务卡" + "." + type;
          that.saveFile(imgData, filename);
        }
      );
    },
    //下载至本地
    saveFile(data, filename) {
      let save_link = document.createElementNS(
        "http://www.w3.org/1999/xhtml",
        "a"
      );
      save_link.href = data;
      save_link.download = filename;
      let event = document.createEvent("MouseEvents");
      event.initMouseEvent(
        "click",
        true,
        false,
        window,
        0,
        0,
        0,
        0,
        0,
        false,
        false,
        false,
        false,
        0,
        null
      );
      save_link.dispatchEvent(event);
    },
  },
};
</script>
